<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>选择菜单</title>
    <link rel="shortcut icon" href="/assets/images/favicon.ico" type="image/x-icon"/>
    <link rel="stylesheet" href="/assets/pear/css/pear.css"/>
    <style>
        .current-selected {
            background-color: #dddddd;
        }
    </style>
</head>
<body>
<form class="layui-form" action="" onsubmit="return false;">
    <div class="mainBox">
        <div class="main-container">
            <div class="flex-row" style="align-content: center;gap: 5px;width: 310px;margin: 5px auto">
                <span>关键词:</span>
                <input type="text" id="search" placeholder="请输入搜索关键词" class="layui-input"
                       style="width: 200px;height: 22px">
                <button type="button" class="layui-btn layui-btn-xs">搜索</button>
            </div>
            <div class="flex-row" style="gap: 5px">
                <span class="layui-text" style="flex: 1">当前选择: <b id="current" style="color: red"></b></span>
                <span id="show" class="layui-text" style="cursor: pointer;color: #1e9fff">展开</span>
                <span>/</span>
                <span id="hide" class="layui-text" style="cursor: pointer;margin-right: 16px;color: #1e9fff">折叠</span>
            </div>
            <div id="treeId" lay-filter="treeId"></div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="pear-btn pear-btn-primary pear-btn-sm" lay-submit=""
                    lay-filter="user-save">
                <i class="layui-icon layui-icon-ok"></i>
                选择
            </button>
            <button id="close" class="pear-btn pear-btn-sm">
                <i class="layui-icon layui-icon-close"></i>
                关闭
            </button>
        </div>
    </div>
</form>
<script src="/assets/layui/layui.js"></script>
<script src="/assets/pear/pear.js"></script>
<script>
    layui.use(['form', 'jquery', 'menuApi'], function () {
        let form = layui.form;
        let $ = layui.jquery;
        var menuApi = layui.menuApi;
        var tree = layui.tree;
        var current = {}
        // 模拟数据
        var data = [];
        var oldData = []
        var spread = false

        var param = {
            elem: '#treeId',
            data: data,
            onlyIconControl: true,
            customName: { // 自定义 data 字段名 --- 2.8.14+
                id: 'menuId',
                title: 'menuName',
                children: 'children'
            },
            click: function (obj) {
                current = obj.data
                console.log(obj.data); // 得到当前点击的节点数据
                $('.layui-tree-entry').removeClass('current-selected');
                let arr = $(obj.elem).find('.layui-tree-entry');
                for (const e of arr) {
                    if ($(e).text() === obj.data.menuName) {
                        $(e).addClass('current-selected')
                        $('#current').html(obj.data.menuName)
                        break
                    }
                }
            }
        }
        // 渲染
        var loadIndex = layer.load(0);
        menuApi.list().then(res => {
            oldData = res.data
            data = res.data
            param.data = listToTree(data, {rootValue: 0, spread: spread})
            tree.render(param)
        }).finally(() => {
            layer.close(loadIndex)
        })

        form.on('submit(user-save)', function (data) {
            if (!current.menuId) {
                layer.msg('您还未选择菜单')
            }
            searchIframeBySrc('menu/edit.html').formIframeData(current)
            closeWindowToMain(window.name)
            return false;
        });
        $('#close').click(() => {
            closeWindowToMain(window.name)
        })
        $('#search').on('input', function () {
            let curr = $(this).val()
            console.log('实时输入:', $(this).val());
            if (!curr) {
                data = oldData
                param.data = listToTree(data, {rootValue: 0, spread: spread})
                tree.render(param)
            } else {
                let temp = oldData.filter(e => {
                    return e.menuName.indexOf(curr) !== -1
                })
                data = listToTree(temp, {rootValue: 0, spread: spread})
                param.data = data
                tree.render(param)
            }
        });
        $('#show').click(() => {
            spread = true
            param.data = listToTree(data, {rootValue: 0, spread: spread})
            tree.render(param)
        })
        $('#hide').click(() => {
            spread = false
            param.data = listToTree(data, {rootValue: 0, spread: spread})
            tree.render(param)
        })
    })

    /**
     * 将扁平的菜单列表转换为树形结构
     * @param {Array} list - 包含菜单数据的数组，每个元素需包含menuId和parentId
     * @param {Object} [options] - 配置选项
     * @param {string} [options.idKey='menuId'] - 节点ID的属性名
     * @param {string} [options.parentKey='parentId'] - 父节点ID的属性名
     * @param {string} [options.childrenKey='children'] - 子节点数组的属性名
     * @param {any} [options.rootValue=null] - 根节点的parentId值
     * @returns {Array} 树形结构的菜单
     */
    function listToTree(list, options) {
        options = options || {};
        var idKey = options.idKey || 'menuId';
        var parentKey = options.parentKey || 'parentId';
        var childrenKey = options.childrenKey || 'children';
        var rootValue = options.rootValue === undefined ? null : options.rootValue;
        var spread = options.spread ? true : false

        // 创建一个映射表，用于快速查找节点
        var nodeMap = {};

        // 最终的树结构
        var tree = [];

        // 第一次遍历：创建节点映射表并初始化children
        for (var i = 0; i < list.length; i++) {
            var item = list[i];
            item.spread = spread
            var newItem = {};

            // 复制所有属性
            for (var key in item) {
                if (item.hasOwnProperty(key)) {
                    newItem[key] = item[key];
                }
            }

            newItem[childrenKey] = [];
            nodeMap[newItem[idKey]] = newItem;
        }

        // 第二次遍历：构建树结构
        for (var j = 0; j < list.length; j++) {
            var currentItem = list[j];
            var current = nodeMap[currentItem[idKey]];

            // 如果当前节点的parentId等于根值，则它是根节点
            if (currentItem[parentKey] === rootValue) {
                tree.push(current);
            } else {
                // 否则，将当前节点添加到其父节点的children中
                var parent = nodeMap[currentItem[parentKey]];
                if (parent) {
                    parent[childrenKey].push(current);
                } else {
                    // 处理找不到父节点的情况（可选）
                    console.warn('找不到节点 ' + currentItem[idKey] + ' 的父节点 ' + currentItem[parentKey]);
                    tree.push(current); // 作为根节点处理
                }
            }
        }

        return tree;
    }
</script>
<script>
</script>
</body>
</html>
